<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>查看策略秘钥 - 币胜客pro</title>
    <link rel="stylesheet" href="styles.css" />
    <style>
      body {
        min-height: 100vh;
        background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      }
      .page-wrap {
        width: min(520px, 92vw);
        background: #ffffff;
        border-radius: 20px;
        padding: 32px;
        box-shadow: 0 24px 60px rgba(15, 23, 42, 0.25);
        display: flex;
        flex-direction: column;
        gap: 24px;
      }
      .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .page-title {
        margin: 0;
        font-size: 24px;
        font-weight: 700;
        color: #0f172a;
      }
      .page-subtitle {
        margin: 4px 0 0;
        color: #475569;
        font-size: 14px;
      }
      .link-btn {
        border: none;
        background: none;
        color: #0ea5e9;
        cursor: pointer;
        font-size: 14px;
        padding: 4px 8px;
      }
      .secret-card {
        background: #f1f5f9;
        border-radius: 12px;
        padding: 20px;
        display: none;
        flex-direction: column;
        gap: 16px;
      }
      .copy-field {
        display: flex;
        gap: 8px;
        align-items: center;
      }
      .copy-field .input,
      .copy-field textarea {
        flex: 1;
      }
      .copy-field button {
        flex: none;
      }
      .muted {
        color: #64748b;
        font-size: 13px;
      }
      @media (max-width: 640px) {
        body { padding: 16px; }
        .page-wrap { padding: 24px; }
        .copy-field {
          flex-direction: column;
          align-items: stretch;
        }
        .copy-field button {
          width: 100%;
        }
      }
    </style>
  </head>
  <body>
    <main class="page-wrap" role="main">
      <header class="page-header">
        <div>
          <h1 class="page-title">策略密钥</h1>
          <p class="page-subtitle" id="page-subtitle">加载中...</p>
        </div>
        <button class="link-btn" id="btn-go-back">← 返回策略管理</button>
      </header>

      <div class="form-msg" id="info-msg" aria-live="polite"></div>

      <section class="secret-card" id="secret-card">
        <strong>秘钥已刷新，请尽快更新 TradingView 设置。</strong>
        <div class="copy-field">
          <input class="input" id="secret-webhook" readonly />
          <button class="btn" type="button" data-copy="webhook">复制 Webhook</button>
        </div>
        <div class="copy-field">
          <textarea class="input" rows="4" id="secret-body" readonly></textarea>
          <button class="btn" type="button" data-copy="body">复制 Body Secret</button>
        </div>
        <p class="muted">提示：旧密钥已失效，更新前请勿泄露此信息。</p>
      </section>
    </main>

    <script>
      (function () {
        'use strict';

        var API_BASE = 'http://43.153.150.144:8080';

        function getToken() {
          try { return localStorage.getItem('token') || ''; } catch (_) { return ''; }
        }

        async function request(method, path, body) {
          var headers = { 'Content-Type': 'application/json' };
          var token = getToken();
          if (token) headers.Authorization = 'Bearer ' + token;
          return fetch(API_BASE + path, {
            method: method,
            headers: headers,
            body: body ? JSON.stringify(body) : undefined
          });
        }

        function copy(text) {
          if (!text) return;
          if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text);
          } else {
            var tmp = document.createElement('textarea');
            tmp.value = text;
            tmp.style.position = 'fixed';
            tmp.style.opacity = '0';
            document.body.appendChild(tmp);
            tmp.select();
            try { document.execCommand('copy'); } catch (_) {}
            document.body.removeChild(tmp);
          }
        }

        var params = new URLSearchParams(location.search);
        var strategyId = params.get('id');
        var subtitle = document.getElementById('page-subtitle');
        var msg = document.getElementById('info-msg');
        var card = document.getElementById('secret-card');
        var webhookInput = document.getElementById('secret-webhook');
        var bodyTextarea = document.getElementById('secret-body');
        var btnBack = document.getElementById('btn-go-back');

        function goBack() {
          if (document.referrer && document.referrer.indexOf('strategy-manager') >= 0) {
            history.back();
          } else {
            window.location.href = 'strategy-manager.html';
          }
        }

        btnBack.addEventListener('click', goBack);

        function setMessage(text, tone) {
          msg.textContent = text || '';
          msg.className = 'form-msg';
          if (tone === 'success') {
            msg.style.color = '#16a34a';
          } else if (tone === 'error') {
            msg.style.color = '#dc2626';
          } else {
            msg.style.color = '#0ea5e9';
          }
        }

        if (!strategyId) {
          subtitle.textContent = '缺少策略 ID';
          setMessage('无法获取密钥：未提供策略 ID。', 'error');
          return;
        }

        subtitle.textContent = '策略 ID：' + strategyId;
        setMessage('正在刷新密钥...', 'info');

        (async function loadSecret() {
          try {
            var res = await request('POST', '/scripts/' + strategyId + '/rotate-secret', {});
            var data = await res.json();
            if (!res.ok) {
              throw new Error((data && data.message) || (data && data.detail) || ('HTTP ' + res.status));
            }
            var origin = location.origin || (location.protocol + '//' + location.host);
            var path = data.webhook_url || '';
            var webhookUrl = /^https?:\/\//i.test(path) ? path : origin.replace(/\/$/, '') + (path ? (path.startsWith('/') ? path : '/' + path) : '');
            webhookInput.value = webhookUrl;
            bodyTextarea.value = JSON.stringify({ secret: data.body_secret || '' }, null, 2);
            card.style.display = 'flex';
            setMessage('密钥获取成功。', 'success');
          } catch (err) {
            setMessage('获取密钥失败：' + (err && err.message ? err.message : '未知错误'), 'error');
          }
        })();

        card.addEventListener('click', function (ev) {
          var target = ev.target;
          if (target && target.matches('button[data-copy="webhook"]')) {
            copy(webhookInput.value);
          } else if (target && target.matches('button[data-copy="body"]')) {
            copy(bodyTextarea.value);
          }
        });
      })();
    </script>
  </body>
</html>
